<template>
  <div class="farm-home-view">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">羊场首页</h2>
        <div class="refresh-status">
          <el-tag 
            :type="autoRefreshEnabled ? 'success' : 'info'" 
            size="small"
            class="refresh-tag"
          >
            <el-icon><Refresh /></el-icon>
            {{ autoRefreshEnabled ? '实时刷新中' : '手动模式' }}
          </el-tag>
          <span class="update-time" v-if="lastUpdateTime">
            最后更新: {{ lastUpdateTime }}
          </span>
          <span class="next-update-time" v-if="autoRefreshEnabled && nextUpdateTime">
            下次更新: {{ nextUpdateTime }}
          </span>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          :type="autoRefreshEnabled ? 'success' : 'info'" 
          size="small" 
          @click="toggleAutoRefresh"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          {{ autoRefreshEnabled ? '关闭实时刷新' : '开启实时刷新' }}
        </el-button>
        <el-button type="primary" size="small" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          立即刷新
        </el-button>
        <el-button type="primary" size="small">
          <el-icon><Setting /></el-icon>
          配置
        </el-button>
      </div>
    </div>

    <el-row :gutter="20" class="dashboard-row">
      <!-- 左侧功能区域 -->
      <el-col :span="8">
        <!-- 常用功能 -->
        <el-card class="function-card">
          <div class="card-title">常用功能</div>
          <div class="function-desc">
            点击右上角"配置"按钮，可以设置显示常用功能，支持图标和文字快速访问。
          </div>
        </el-card>

        <!-- 生产提示 -->
        <el-card class="reminder-card">
          <div class="card-title">生产提示</div>
          <div class="reminder-list">
            <div class="reminder-item">
              <el-icon class="reminder-icon" style="color: #f56c6c;"><House /></el-icon>
              <span class="reminder-text">待配种</span>
              <span class="reminder-count" :class="{ 'data-update': dataUpdateAnimation }">{{ pendingBreedingCount }}</span>
            </div>
            <div class="reminder-item">
              <el-icon class="reminder-icon" style="color: #409eff;"><Document /></el-icon>
              <span class="reminder-text">待首次妊检</span>
              <span class="reminder-count" :class="{ 'data-update': dataUpdateAnimation }">{{ pendingFirstCheckCount }}</span>
            </div>
            <div class="reminder-item">
              <el-icon class="reminder-icon" style="color: #e6a23c;"><House /></el-icon>
              <span class="reminder-text">待分娩</span>
              <span class="reminder-count" :class="{ 'data-update': dataUpdateAnimation }">{{ pendingLambingCount }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 中间存栏信息 -->
      <el-col :span="8">
        <el-card class="inventory-card">
          <div class="inventory-header">
            <div class="inventory-title">羊场实时存栏</div>
          </div>
          <div class="total-inventory">
            <div class="total-number" :class="{ 'data-update': dataUpdateAnimation }">{{ totalInventory }}</div>
            <div class="total-unit">只</div>
          </div>
          <div class="inventory-change">
            <span class="change-text">{{ growthRate.total }}% 同比上周</span>
          </div>
          <div class="inventory-breakdown">
            <div class="breakdown-item">
              <span class="breakdown-label">种母存栏</span>
              <span class="breakdown-value" :class="{ 'data-update': dataUpdateAnimation }">{{ breedingEweCount }}</span>
            </div>
            <div class="breakdown-item">
              <span class="breakdown-label">后裔存栏</span>
              <span class="breakdown-value" :class="{ 'data-update': dataUpdateAnimation }">{{ offspringCount }}</span>
            </div>
            <div class="breakdown-item">
              <span class="breakdown-label">种公存栏</span>
              <span class="breakdown-value" :class="{ 'data-update': dataUpdateAnimation }">{{ breedingRamCount }}</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧种母存栏变动 -->
      <el-col :span="8">
        <el-card class="change-card">
          <div class="card-title">种母存栏变动</div>
          <div class="chart-container">
            <div ref="breedingEweChangeChartRef" class="chart" style="height: 200px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <el-col :span="12">
        <el-card class="dashboard-section">
          <div class="section-title">近30日存栏趋势</div>
          <div class="chart-container">
            <div ref="inventoryChartRef" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="dashboard-section">
          <div class="section-title">近30日死淘趋势</div>
          <div class="chart-container">
            <div ref="mortalityChartRef" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="dashboard-row">
      <el-col :span="12">
        <el-card class="dashboard-section">
          <div class="section-title">种母存栏结构</div>
          <div class="structure-header">
            <el-select v-model="selectedBreed" placeholder="全部品种" size="small">
              <el-option label="全部品种" value="all" />
              <el-option label="澳洲白" value="australian_white" />
              <el-option label="杜泊" value="dorper" />
              <el-option label="萨福克" value="suffolk" />
            </el-select>
          </div>
          <div class="chart-container">
            <div ref="structureChartRef" class="chart" style="height: 300px;"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="dashboard-section">
          <div class="section-title">本月统计</div>
          <div class="monthly-stats">
            <div class="stat-item">
              <div class="stat-label">本月新增</div>
              <div class="stat-value">{{ monthlyNewCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">本月销售</div>
              <div class="stat-value">{{ monthlySalesCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">本月死亡</div>
              <div class="stat-value">{{ monthlyDeathCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">本月淘汰</div>
              <div class="stat-value">{{ monthlyEliminationCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Setting, Document, House } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getTotalInventory,
  getBreedingEweCount,
  getReserveCount,
  getInventoryTrend,
  getMortalityTrend,
  getBreedingEweStructure,
  getBreedingEweChangeData,
  getLastWeekData,
  calculateGrowthRate,
  getFarmOverview,
  getMonthlyNewSheep,
  getMonthlySales
} from '@/utils/requestDashboard'

// 响应式数据
const loading = ref(false)
const totalInventory = ref(136)
const breedingEweCount = ref(34)
const offspringCount = ref(68)
const breedingRamCount = ref(34)
const reserveCount = ref(0)
const growthRate = ref({
  total: 0,
  breedingEwe: 0,
  reserve: 0
})

// 生产提示数据
const pendingBreedingCount = ref(1)
const pendingFirstCheckCount = ref(1)
const pendingLambingCount = ref(1)

// 本月统计数据
const monthlyNewCount = ref(0)
const monthlySalesCount = ref(0)
const monthlyDeathCount = ref(0)
const monthlyEliminationCount = ref(0)

// 品种选择
const selectedBreed = ref('all')

// 自动刷新相关
const autoRefreshInterval = ref<number | null>(null)
const autoRefreshEnabled = ref(true)
const lastUpdateTime = ref<string>('')

// 数据更新动画相关
const dataUpdateAnimation = ref(false)
const updateCount = ref(0)

// 实时监控相关
const connectionStatus = ref('connected')
const nextUpdateTime = ref<string>('')

// 图表实例
const inventoryChartRef = ref<HTMLElement>()
const mortalityChartRef = ref<HTMLElement>()
const structureChartRef = ref<HTMLElement>()
const breedingEweChangeChartRef = ref<HTMLElement>()
let inventoryChart: echarts.ECharts | null = null
let mortalityChart: echarts.ECharts | null = null
let structureChart: echarts.ECharts | null = null
let breedingEweChangeChart: echarts.ECharts | null = null

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (inventoryChartRef.value) {
      inventoryChart = echarts.init(inventoryChartRef.value)
    }
    if (mortalityChartRef.value) {
      mortalityChart = echarts.init(mortalityChartRef.value)
    }
    if (structureChartRef.value) {
      structureChart = echarts.init(structureChartRef.value)
    }
    if (breedingEweChangeChartRef.value) {
      breedingEweChangeChart = echarts.init(breedingEweChangeChartRef.value)
    }
  })
}

// 更新存栏趋势图表
const updateInventoryChart = (data: any[]) => {
  if (!inventoryChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        const date = params[0].axisValue
        const value = params[0].value
        return `${date}<br/>存栏: ${value}`
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 150
    },
    series: [{
      data: data.map(item => item.value),
      type: 'line',
      smooth: true,
      areaStyle: {
        opacity: 0.3
      },
      itemStyle: {
        color: '#409EFF'
      }
    }]
  }
  
  inventoryChart.setOption(option)
}

// 更新死淘趋势图表
const updateMortalityChart = (data: any[]) => {
  if (!mortalityChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params: any) {
        const date = params[0].axisValue
        let result = `${date}<br/>`
        params.forEach((param: any) => {
          result += `${param.seriesName}: ${param.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: ['死亡数', '淘汰数']
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 2
    },
    series: [
      {
        name: '死亡数',
        data: data.map(item => item.death),
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#f56c6c'
        }
      },
      {
        name: '淘汰数',
        data: data.map(item => item.culling),
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  mortalityChart.setOption(option)
}

// 更新种母存栏结构图表
const updateStructureChart = (data: any) => {
  if (!structureChart) return
  
  // 将对象格式转换为数组格式
  const chartData = [
    { name: '待配种', value: data.pendingBreeding || 12 },
    { name: '待首次妊检', value: data.pendingFirstCheck || 8 },
    { name: '待二次妊检', value: data.pendingSecondCheck || 6 },
    { name: '待上产床', value: data.pendingLambingBed || 4 },
    { name: '待分娩', value: data.pendingLambing || 2 },
    { name: '种母待断奶', value: data.pendingWeaning || 3 },
    { name: '妊娠换料', value: data.gestationFeedChange || 1 }
  ]
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: chartData.map(item => item.name)
    },
    series: [{
      name: '种母存栏结构',
      type: 'pie',
      radius: '50%',
      data: chartData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  structureChart.setOption(option)
}

// 更新种母存栏变动图表
const updateBreedingEweChangeChart = (data: any) => {
  if (!breedingEweChangeChart) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: [`期初 (${data.summary.initial}只)`, `期末 (${data.summary.final}只)`]
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.categories
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: `期初 (${data.summary.initial}只)`,
        type: 'bar',
        data: data.initial,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: `期末 (${data.summary.final}只)`,
        type: 'bar',
        data: data.final,
        itemStyle: {
          color: '#E6A23C'
        }
      }
    ]
  }
  
  breedingEweChangeChart.setOption(option)
}

// 获取所有数据
const fetchAllData = async () => {
  loading.value = true
  try {
    const [
      totalInventoryData,
      breedingEweData,
      reserveData,
      inventoryTrendData,
      mortalityTrendData,
      structureData,
      breedingEweChangeData,
      lastWeekData,
      monthlyNewData,
      monthlySalesData
    ] = await Promise.all([
      getTotalInventory(),
      getBreedingEweCount(),
      getReserveCount(),
      getInventoryTrend(),
      getMortalityTrend(),
      getBreedingEweStructure(),
      getBreedingEweChangeData(),
      getLastWeekData(),
      getMonthlyNewSheep(),
      getMonthlySales()
    ])

    totalInventory.value = totalInventoryData
    breedingEweCount.value = breedingEweData
    reserveCount.value = reserveData
    monthlyNewCount.value = monthlyNewData
    monthlySalesCount.value = monthlySalesData

    growthRate.value = {
      total: calculateGrowthRate(totalInventoryData, lastWeekData.totalInventory),
      breedingEwe: calculateGrowthRate(breedingEweData, lastWeekData.breedingEweCount),
      reserve: calculateGrowthRate(reserveData, lastWeekData.reserveCount)
    }

    updateInventoryChart(inventoryTrendData)
    updateMortalityChart(mortalityTrendData)
    updateStructureChart(structureData)
    updateBreedingEweChangeChart(breedingEweChangeData)

    // 触发数据更新动画
    dataUpdateAnimation.value = true
    updateCount.value++
    
    lastUpdateTime.value = new Date().toLocaleString('zh-CN')
    
    // 如果是自动刷新，显示静默更新提示
    if (autoRefreshEnabled.value) {
      console.log(`数据已自动更新 (第${updateCount.value}次)`)
      updateNextUpdateTime() // 更新下次更新时间
    } else {
      ElMessage.success('数据刷新成功')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    if (!autoRefreshEnabled.value) {
      ElMessage.error('数据获取失败，请稍后重试')
    }
  } finally {
    loading.value = false
    // 动画结束后重置状态
    setTimeout(() => {
      dataUpdateAnimation.value = false
    }, 1000)
  }
}

// 手动刷新数据
const refreshData = () => {
  fetchAllData()
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefreshEnabled.value = !autoRefreshEnabled.value
  if (autoRefreshEnabled.value) {
    startAutoRefresh()
    ElMessage.success('已开启自动刷新')
  } else {
    stopAutoRefresh()
    ElMessage.info('已关闭自动刷新')
  }
}

// 开始自动刷新
const startAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value)
  }
  
  // 立即执行一次
  fetchAllData()
  
  // 设置定时器
  autoRefreshInterval.value = setInterval(() => {
    fetchAllData()
  }, 30 * 1000) // 每30秒刷新一次，更实时
  
  // 计算下次更新时间
  updateNextUpdateTime()
}

// 更新下次更新时间
const updateNextUpdateTime = () => {
  const now = new Date()
  const nextUpdate = new Date(now.getTime() + 30 * 1000)
  nextUpdateTime.value = nextUpdate.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshInterval.value) {
    clearInterval(autoRefreshInterval.value)
    autoRefreshInterval.value = null
  }
}

// 监听窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (inventoryChart) inventoryChart.resize()
  if (mortalityChart) mortalityChart.resize()
  if (structureChart) structureChart.resize()
  if (breedingEweChangeChart) breedingEweChangeChart.resize()
}

onMounted(() => {
  initCharts()
  fetchAllData()
  startAutoRefresh()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  stopAutoRefresh()
  if (inventoryChart) inventoryChart.dispose()
  if (mortalityChart) mortalityChart.dispose()
  if (structureChart) structureChart.dispose()
  if (breedingEweChangeChart) breedingEweChangeChart.dispose()
})
</script>

<style scoped>
.farm-home-view {
  padding: 24px;
  background: #f6f8fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 0 16px 0;
  border-bottom: 1px solid #e4e7ed;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.refresh-status {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.refresh-tag {
  display: flex;
  align-items: center;
  gap: 4px;
}

.update-time {
  font-size: 12px;
  color: #909399;
}

.next-update-time {
  font-size: 12px;
  color: #67C23A;
  font-weight: 500;
}

.dashboard-row {
  margin-bottom: 20px;
}

.dashboard-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}

.chart-container {
  position: relative;
}

.chart {
  width: 100%;
}

/* 功能卡片样式 */
.function-card, .reminder-card, .inventory-card, .change-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #303133;
}

.function-desc {
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.reminder-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reminder-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
}

.reminder-icon {
  font-size: 16px;
}

.reminder-text {
  flex: 1;
  font-size: 14px;
  color: #606266;
}

.reminder-count {
  background: #f56c6c;
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

/* 存栏信息样式 */
.inventory-header {
  margin-bottom: 16px;
}

.inventory-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.total-inventory {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 12px;
}

.total-number {
  font-size: 36px;
  font-weight: 700;
  color: #409EFF;
}

.total-unit {
  font-size: 16px;
  color: #606266;
}

.inventory-change {
  margin-bottom: 16px;
}

.change-text {
  font-size: 14px;
  color: #909399;
}

.inventory-breakdown {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.breakdown-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.breakdown-item:last-child {
  border-bottom: none;
}

.breakdown-label {
  font-size: 14px;
  color: #606266;
}

.breakdown-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

/* 结构图表头部 */
.structure-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 本月统计样式 */
.monthly-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #409EFF;
}

/* 数据更新动画 */
.data-update {
  animation: dataUpdatePulse 1s ease-in-out;
}

@keyframes dataUpdatePulse {
  0% {
    transform: scale(1);
    color: inherit;
  }
  50% {
    transform: scale(1.05);
    color: #67C23A;
    font-weight: 700;
  }
  100% {
    transform: scale(1);
    color: inherit;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .farm-home-view {
    padding: 16px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .monthly-stats {
    grid-template-columns: 1fr;
  }
  
  .total-number {
    font-size: 28px;
  }
}
</style> 